package com.zxw.mvpproject.mvp.presenter;

import android.content.Context;
import android.content.Intent;

import com.zxw.mvpproject.mvp.bean.Book;
import com.zxw.mvpproject.mvp.manager.DataManager;
import com.zxw.mvpproject.mvp.view.BookView;
import com.zxw.mvpproject.mvp.view.View;

import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * 创建时间 ：2018/5/3.
 * 创建人 ：${zxw}.
 * 功能描述：
 */

public class BookPresenter implements Presenter {

    private Context mContext;
    private DataManager dataManager;
    private BookView bookView;
    private Book mBook;
    private CompositeSubscription compositeSubscription;

    public BookPresenter(Context context) {
        mContext = context;
    }

    @Override
    public void onCreate() {
        dataManager = new DataManager(mContext);
        compositeSubscription = new CompositeSubscription();
    }

    @Override
    public void onStart() {

    }

    @Override
    public void onStop() {
        if(compositeSubscription.hasSubscriptions()){
            compositeSubscription.unsubscribe();
        }
    }

    @Override
    public void pause() {

    }

    @Override
    public void attachView(View view) {
        bookView = (BookView)view;
    }


    @Override
    public void attachIncomingIntent(Intent intent) {

    }

    public void getSearchBook(String name,String tag,int count,int start){
        compositeSubscription.add(dataManager.getSearchBook(name,tag,count,start)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Subscriber<Book>() {
                    @Override
                    public void onCompleted() {
                        if(mBook!=null){
                            bookView.success(mBook);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        bookView.fail("请求失败！！");
                    }

                    @Override
                    public void onNext(Book book) {
                        mBook = book;
                    }
                }));
    }
}
